package test7;

import java.io.*;
import java.util.Base64;
import java.util.Properties;
import java.util.Set;

public class Test {
    public static void main(String[] args) throws IOException {
        //1.用Base64Demo提供的加密方法对value值进行加密，把加密后的数据覆盖到原properties文件中

        String path = "stream-test\\prop.properties";
        Properties prop = new Properties();
        FileReader fr = new FileReader(path);
        prop.load(fr);
        Set<Object> keys = prop.keySet();
        for (Object key : keys) {
            Object value = prop.get(key);
            String newValue = encrypt((String) value);
            prop.put(key, newValue);
        }

        FileWriter fw = new FileWriter(path);

        prop.store(fw, null);
        //2.读取加密后的properties中的数据，把加密的密文进行解密 打印在控制台
        FileReader fr2 = new FileReader(path);

        prop.load(fr2);
        Set<Object> keys2 = prop.keySet();
        for (Object key : keys2) {
            Object value = prop.get(key);
            String oldValue = decode((String) value);
            prop.put(key,oldValue);
        }
            System.out.println(prop);
    }


    //加密方法
    public static String encrypt(String str) {
        //创建加密对象
        Base64.Encoder base64 = Base64.getEncoder();
        //获取加密后的字节数组
        byte[] encode = base64.encode(str.getBytes());
        //把密文转换为字符串
        String s = new String(encode);
        //返回
        return s;
    }

    //解密方法
    public static String decode(String str) {
        //创建解密对象
        Base64.Decoder decoder = Base64.getDecoder();
        //获取解密字节数组
        byte[] decode = decoder.decode(str);
        //获取原文
        String s = new String(decode);
        //返回
        return s;
    }
}
